package org.psyduck.controller.common;

import com.alibaba.fastjson.JSON;
import org.psyduck.common.annotation.NotResponseAdvice;
import org.psyduck.common.utils.FileUtils;
import org.psyduck.common.utils.Global;
import org.psyduck.common.utils.OSSUtils;
import org.psyduck.common.utils.WebUtils;
import org.psyduck.ueditor.UeditorConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/ueditor")
@NotResponseAdvice
public class UEditorController {

    @Autowired
    OSSUtils ossUtils;

	@RequestMapping("main")
	public void main(String action, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		request.getRequestDispatcher("/ueditor/"+action).forward(request, response);
	}
	
	@RequestMapping(value = "/config",produces = "text/javascript")
	@ResponseBody
	public String config(String callback){
		if(null == callback || "".equals(callback)) {
			return JSON.toJSONString(new UeditorConfig());
		}
		return callback+"("+JSON.toJSONString(new UeditorConfig())+")";
	}
	
	@RequestMapping("/uploadImage")
	@ResponseBody
	public String uploadImage(@RequestParam("file") MultipartFile file) {
		return JSON.toJSONString(saveFile(file));
	}
	
	@RequestMapping("/uploadFile")
	@ResponseBody
	public String uploadFile(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException{
		return JSON.toJSONString(saveFile(file));
	}

	public Map<String, String> saveFile(MultipartFile file) {
        Map<String, String> map = new HashMap<>();
        if(Global.UPLOAD_TYPE.equals("oss") && !ossUtils.isDefault()){
            try {
                map = ossUtils.uploadFileToOss(file.getOriginalFilename(),file.getBytes(),file.getInputStream());
                map.put("url", map.get("url").replace(WebUtils.getUeditorPrefix(), ""));
                map.put("state", "SUCCESS");
                map.put("original", file.getName());
                map.put("name", file.getName());
                map.put("size", file.getSize() + "");
            }catch (Exception ignore){}
        }else{
            map = FileUtils.saveFile(file);
        }
        return map;
    }

}
